<?php


namespace app\api\model;


use app\api\help\Http;
use think\facade\Log;

class AllInPay
{
    const APPID      = '00270688';
    const CUSID      = '6601210481612X9';
    const APIURL     = "https://vsp.allinpay.com/apiweb/unitorder";   //生产环境
    const REFUND_URL = "https://vsp.allinpay.com/apiweb/tranx/refund";//生产环境
    const APIVERSION = '11';
    const PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm9OV6zH5DYH/ZnAVYHscEELdCNfNTHGuBv1nYYEY9FrOzE0/4kLl9f7Y9dkWHlc2ocDwbrFSm0Vqz0q2rJPxXUYBCQl5yW3jzuKSXif7q1yOwkFVtJXvuhf5WRy+1X5FOFoMvS7538No0RpnLzmNi3ktmiqmhpcY/1pmt20FHQQIDAQAB';
    
    
    const PRIVATE_KEY = 'MIIEowIBAAKCAQEAtVRmJNIXOWdfBv8r5xfRIrTrVV4v56hwCHUW2v4H7DFUSiHJ7YxZxc/MqRuX1vwjm3xDkbx8VAxCrpsRdcdAaz79L93astPUWVHWLC/jt8uhZc9PXYx+ZGhn42hDG1bNe7W4sCez3bDYVMU1D0xWPBCHPFLA94beE3A4RnMDuj7oNbgtQSLYlZhbXmb3Cw9IULoc2yyx9H3PSab/4Y1ObkWw3gDag2ew7lXI55pmCBlFdV72hjaO/Y9aegKtXRT6ApIloskmgx7at246T2VmxK4PhbbnL/WWKPEsl+Kn9FJN3nYeCqtqKyH9RVqjyW3B5IhVChrF4yUNPfZEh5z4fwIDAQABAoIBABzMx+BnQesLIQuycZ2lqcDSbWJEsGUh2pFtT3D+0fFQsGuJzFGfbg69/2qIiGhL6bfjV7QI9NJAlEK5PF+xgujFu17j5L1saZi6J8Mi5A8oF31dHOTl0JlP/9gdkjMAaWiRp0DLPYUjdmiYXeINJNErat9I4X8u+4yo0TdXQytMV10PcUHCr6xqYPdPNubejxZyRtvqJwne8m2gHcyG15vyv0K6J8ohOo0AQNtG4dXx6KwMuRDnQPiq8hgh1um0sS9oK1Asvop66AMfG4X0o7Sh1425qugKxcoas4ET9osg8a4pUmFYoPve5I3XBSNATNGS/hGfwOk1/kz4bnFvMnECgYEA+MdXeJ13HzdHNXUBBaL+22MmSYZAJt+8EyceZNpK0AklHguTlBmRsbiK1NG5+QofEKmOt+VAOl1iRKFRKY4PPsFU+VNINuvqhIq3LrA852gWgagjj1VlQPP2HBrkD6wre4/TQfBuK69LYNJJly+RAIbSOpi+HDaSteJIcyoHmakCgYEAupfZIpg2GrvlcO5vgUFdxma4EdhhEj/rdrddHN6QuWbEKxjUXF5yysthAW1Qq6M08kUmqlwwcxM6t2Dr+VSaSFL8uAVswEppIMe6i+cqbJb3Bh3iObuudvpJgS8Ro9a8ezeEhZz7M2dz7dzOnwDHIqnVsN6pmsVdZvOgv4nDaecCgYB4bpfrrd7y36G7QS8DeYqCzhbE1RbNOtYjN3bBP+Ojnim3x8bjlRUwwbODnxu2ca3kNRD/+R0EpBxkOOu/gCPlL1ZhdG2rGL3o9/YBxhNVus/aaHj+dEqWDQQBSwtIgwJxyIhujWPoBe4pquMxKze414uCDltJ8SlIn4iPJ7OSMQKBgHI4vgy1THl1B/DnpI5lKzhmbMtPv6xiQIt9l5wyijlUNUWEf4rDrlWBxjIPbtCCqcicmBy1LltjLBBRXmJUbdVUJ6umdnoHku8kFIfLzGaIy1KNPIzG3PesIw7Xd17p9pse0xrPi95dt9Ol1T30RfJsMImC5CQAKTr6bC6T8HGFAoGBANS7iYm4Uf7QNOuZwdV+udJyacYzhdtVVR8fc1u3//GmAMqAb1FAKKYEnC73caCezg1nkc3HqLiWIy4r8MxzWd+cKfrdcLFKTdx0tbSHLrPacMCid3/cwhdKZ5vhsxryAr5h7dpsBAHoq1Mpqsh8eozzzb1sf3/By4vhWuvJ0BF0';
    /**
     * 将参数数组签名
     */
    
    //RSA签名
    public static function Sign(array $array)
    {
        ksort($array);
        $bufSignSrc  = self::ToUrlParams($array);
        $private_key = self::PRIVATE_KEY;
        $private_key = chunk_split($private_key, 64, "\n");
        $key         = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($private_key) . "-----END RSA PRIVATE KEY-----";
        //   echo $key;
        if (openssl_sign($bufSignSrc, $signature, $key)) {
//            		echo 'sign success';
        } else {
            echo 'sign fail';
        }
        $sign = base64_encode($signature);//加密后的内容通常含有特殊字符，需要编码转换下，在网络间通过url传输时要注意base64编码是否是url安全的
//echo $sign;
// echo $signature,"\n";
        return $sign;
        
    }
    
    
    public static function ToUrlParams(array $array)
    {
        $buff = "";
        foreach ($array as $k => $v) {
            if ($v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }
        
        $buff = trim($buff, "&");
        return $buff;
    }
    
    /**
     * 校验签名
     * @param array 参数
     * @param unknown_type appkey
     */
    
    
    public static function ValidSign(array $array)
    {
        $sign = $array[ 'sign' ];
        unset($array[ 'sign' ]);
        ksort($array);
        $bufSignSrc = self::ToUrlParams($array);
        $public_key = self::PUBLIC_KEY;
        $public_key = chunk_split($public_key, 64, "\n");
        $key        = "-----BEGIN PUBLIC KEY-----\n$public_key-----END PUBLIC KEY-----\n";
        $result     = openssl_verify($bufSignSrc, base64_decode($sign), $key);
        return $result;
    }
    /**
     * 获取微信支付信息
     * @param $payData
     * @param $openId
     * @return array
     * @throws Exception
     */
    public static function getPayInfo($payData, $openId)
    : array
    {
        $params                 = [];
        $params[ "cusid" ]      = self::CUSID;
        $params[ "appid" ]      = self::APPID;
        $params[ "version" ]    = self::APIVERSION;
        $params[ "orgid" ]      = '';
        $params[ "trxamt" ]     = $payData[ 'total_amount' ];
        $params[ "reqsn" ]      = $payData[ 'order_no' ];
        $params[ "paytype" ]    = 'W06';
        $params[ "body" ]       = $payData[ 'subject' ];
        $params[ "remark" ]     = $payData[ 'subject' ];
        $params[ "validtime" ]  = 12;
        $params[ "acct" ]       = $openId;
        $params[ "notify_url" ] = 'https://tg.aipintuangou.com/api/order/allInPayNotify';
        $params[ "front_url" ]  = 'https://tg.aipintuangou.com/h5/result.html';
        $params[ "limit_pay" ]  = '';
        $params[ "sub_appid" ]  = 'wx07556a5ac76abe4e';
        $params[ "subbranch" ]  = '';
        $params[ "cusip" ]      = '';
        $params[ "idno" ]       = '';
        $params[ "truename" ]   = '';
        $params[ "fqnum" ]      = '';
        $params[ "randomstr" ]  = 12;
        $params[ "signtype" ]   = 'RSA';
        $params[ "sign" ]       = urlencode(self::Sign($params));//签名
        $paramsStr              = self::ToUrlParams($params);
        $url                    = self::APIURL . "/pay";
        $rsp                    = Http::request($url, 'post', $paramsStr);
        $rspArray               = json_decode($rsp, true);
        if (self::validSign($rspArray)) {
//            halt($rspArray);
//            halt(json_decode($rspArray['payinfo'],true));
            return json_decode($rspArray[ 'payinfo' ], true);
        }
    }
    
    /**
     * 退款处理
     * @param $payData
     * @return array
     * @throws \Yansongda\Pay\Exception\ContainerException
     * @throws \Yansongda\Pay\Exception\InvalidParamsException
     * @throws \Yansongda\Pay\Exception\ServiceNotFoundException
     */
    public static function orderRefundInfo($payData)
    : array
    {
        if ( !is_array($payData)) {
            
            $payData = $payData->toArray();
        }
        $params                = [];
        $params[ "cusid" ]     = self::CUSID;
        $params[ "appid" ]     = self::APPID;
        $params[ "version" ]   = self::APIVERSION;
        $params[ "orgid" ]     = '';
        $params[ "trxamt" ]    = $payData[ 'pay_price' ];
        $params[ "reqsn" ]     = $payData[ 'order_no' ];
        $params[ "oldreqsn" ]  = $payData[ 'order_no' ];
        $params[ "randomstr" ] = 12;
        $params[ "signtype" ]  = 'RSA';
        $params[ "sign" ]      = urlencode(self::Sign($params));//签名
        $paramsStr             = self::ToUrlParams($params);
        $url                   = self::REFUND_URL;
        $rsp                   = Http::request($url, 'post', $paramsStr);
        $rspArray              = json_decode($rsp, true);
        if (self::validSign($rspArray)) {
            return $rspArray;
        }
    }
    /**
     * 退款后
     * @param $order
     * @throws \think\Exception
     */
    public static function afterRefund( $order)
    {
        //取出订单id
        $orderId = $order[ 'id' ];
        //订单编号
        $orderNo = $order[ 'order_no' ];
        //用户ID
        $userId = $order[ 'user_id' ];
        //余额支付部分
        $payBalance = $order[ 'pay_balance' ];
        //判断状态
        if ( !in_array($order[ 'order_status' ], [70, 40])) {
            //多方支付异步重复 记录日志
            $msg = 'pay notify repeat: ' . $orderNo;
            Log::warning($msg);
            exit("fail");
        }
        $balance = MallUser::where('id', $userId)->value('balance');
        
        //修改订单状态
        if ($order[ 'order_status' ] == 70) {
            $type1 = 10;
            $type2 = 11;
        } else {
            //添加失败奖励
            $type1 = 12;
            $type2 = 13;
        }
        //添加交易记录
        MallTradeRecordLog::addRecord($userId, $orderId, $order[ 'pay_price' ], 0, $type1);
        if ($payBalance > 0) {
            $addBalance = $balance + $payBalance;
            //加上余额
            if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $addBalance])) {
                _throwNewException('订单支付失败3');
            }
            //添加交易记录
            MallTradeRecordLog::addRecord($userId, $orderId, $payBalance, $addBalance, $type2);
        }

    }
}